<template>
  <div>
    <h1>实时语音对话</h1>
    <textarea id="inputs" style="width: 400px;height: 200px"> hell world</textarea>
    <br>
    <textarea id="output" style="width: 400px;height: 200px"></textarea>
    <br>
    <button @click="startStream()">get-stream</button>

  </div>
</template>

<script>
import PCMPlayer from "@/views/audio/js/pcmPlayer";
export default {
  name:"audio-test",
  data() {
    return {
      isRecording: false,
      mediaRecorder: null,
      audioChunks: [],
      audioBlob: null,
      socket: null,
    };
  },
  methods: {
    async  startStream() {
      let url = 'http://127.0.0.1:8081/sse/mitter/stream-sse-sink-tts'
      const question = document.getElementById("inputs").value;
      const response = await fetch(url, {
        method: 'POST',
        body: question
      });

      let player = new PCMPlayer({
        encoding: "16bitInt",
        channels: 1,
        sampleRate: 22050,
        flushingTime: 180
      });


      const reader = response.body.getReader();

      let out = document.getElementById("output");
      let tempResult = ''
      let text = ''
      while (true) {
        const {done, value} = await reader.read();
        if (done) {
          console.log("done",out,text)
          break;
        }
        const decoder = new TextDecoder('utf-8')
        let str = decoder.decode(value, {stream: true})
        tempResult += str
        const split = tempResult.match(/data:.*}\n\n/g)

        if (split) {
          str = split.join('')
          tempResult = tempResult.replace(str, '')
        }else {
          continue;
        }

        if (str && str.startsWith('data:')) {
          if (split) {
            for (const index in split) {
              const chunk = JSON?.parse(split[index].replace('data:', ''))

              console.log(chunk)
              if (chunk.text!==""){
                text += chunk.text
                out.value = text;
              }else{
                let uint8Array = Uint8Array.from(atob(chunk.data), (c) => c.charCodeAt(0));
                // console.log("test",chunk,uint8Array)
                player.feed(uint8Array);
              }
            }
          }
        }

      }
    }
  },
  mounted() {
  },
};
</script>